package com.tjtt.tdm.flow.action;

import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.jdom.Document;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.PubMethod;
import com.tjtt.tdm.flow.bean.Flowtype;
import com.tjtt.tdm.flow.service.IFlowtypeService;
import com.tjtt.tdm.flow.service.impl.FlowtypeServiceImpl;

public class FlowtypeAction extends BaseAction {
	private IFlowtypeService flowtypeService;
	private String state;
	private String path;
	private String oldstate;

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getOldstate() {
		return oldstate;
	}

	public void setOldstate(String oldstate) {
		this.oldstate = oldstate;
	}



	public void GetFlowTypeList()
	{
		try{ 
			Map<String, String> filterMap = getPagerMap();
			//查询出所有数据
			String[] viewArray = {"ID","FLOWNAME","FILENAME"};
			String returnStr = "";
			
			PageResult result = flowtypeService.GetFlowtypeList(filterMap);
			returnStr = getColumnJson(result, viewArray);
			
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void DelFlowTypeById()
	{
		try{
			PrintWriter out= getResponse().getWriter();
			HttpServletRequest request = getRequest();
			String id = request.getParameter("id");
			flowtypeService.executeSQL("delete from flow_flowtype where id="+id);
			out.print("{\"ajaxResult\":\"success\"}");
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
		}
	}
	
	public void SaveXml()
	{
		try{
			HttpServletRequest request = this.getRequest();
			PrintWriter out = PubMethod.GetPrintWriter();
			String flowname = request.getParameter("typename");
			flowname = PubMethod.GetDecodeString(flowname);
			String typeid = request.getParameter("typeid");
			if (typeid!=null&&!typeid.equals(""))
			{
				Flowtype entity = flowtypeService.GetFlowtypeById(Long.parseLong(typeid));
				String fileName= entity.getFilename();
				String pathUrl = PubMethod.GetWebPath();
				String filePath = pathUrl+"\\flow\\data\\"+fileName;
				PubMethod.SaveSampleStreamFile(filePath);
				entity.setFlowname(flowname);
				flowtypeService.update(entity);
				flowtypeService.executeSQL("delete from flow_role_right where flowid="+typeid);
				flowtypeService.executeSQL("delete from flow_user_right where flowid="+typeid);
				SAXReader reader = new SAXReader();
			    org.dom4j.Document document =  reader.read(new File(filePath));
			    List list = document.selectNodes("//TopFlow/Procs/Proc/BaseProperties");
			    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
			    	Node node = (Node ) iter.next();
		            String roleids = node.valueOf("@roleid");
		            String statename = node.valueOf("@text");
		            String stateid = node.valueOf("@id");
		        }
			}
			else
			{
				String fileName= PubMethod.GetTimerName();
				String pathUrl = PubMethod.GetWebPath();
				String filePath = pathUrl+"\\flow\\data\\"+fileName+".xml";
				PubMethod.SaveSampleStreamFile(filePath);
				Flowtype entity = new Flowtype();
				entity.setFilename(fileName+".xml");
				entity.setFlowname(flowname);
				typeid = flowtypeService.save(entity);
			}
			out.print(java.net.URLDecoder.decode("操作成功！","UTF-8"));
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
		}
	}
	
	public void SaveXmlChild()
	{
		try{
			HttpServletRequest request = this.getRequest();
			PrintWriter out = PubMethod.GetPrintWriter();
			String fileName= PubMethod.GetTimerName();
			String pathUrl = PubMethod.GetWebPath();
			String filePath = pathUrl+"\\resources\\FlowManage\\data\\"+fileName+".xml";
			PubMethod.SaveSampleStreamFile(filePath);
			
			out.print(fileName+".xml");
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public String GeViewFlowInfo()
	{
		try{
			String ids = this.getRequest().getParameter("id");
			List lists = flowtypeService.findAllBySql("select state,path from flowinstance where id= '"+ids+"'");
			if (lists.size()>0)
			{
				Object[] entity = (Object[] )lists.get(0);
				this.state = entity[0].toString();
				this.path = entity[1].toString();
			}
			List listDetail = flowtypeService.findAllBySql("select statusbefore from flow_detailed where instanceid="+ids);
			String opath = "";
			for(int i=0;i<listDetail.size();i++)
			{
				String entity = listDetail.get(i).toString();
				if (i==0)
				{
					opath+=entity.toString();
				}
				else
				{
					opath+=","+entity.toString();
				}
			}
			this.oldstate = opath;
			return "viewflow";
		}
		catch(Exception exp)
		{
			exp.printStackTrace();
			return "error";
		}
	}
	
	public void GetStateTree() throws Exception
	{
		String userid = ServletActionContext.getRequest().getSession().getAttribute("TDM_USER_ID").toString();
		String strSql = "select t2.id,t2.FLOWNAME,t1.statename,t1.flowid,t1.stateid from flow_role_right t1 left join FLOW_FLOWTYPE t2 on t1.flowid=t2.id union";
	    strSql += " select t4.id,t4.FLOWNAME,t3.statename,t3.flowid,t3.stateid from flow_user_right t3 left join FLOW_FLOWTYPE t4 on t3.flowid=t4.id where t3.userid='"+userid+"'";
	    
	    String typeSql = "select distinct flowid,FLOWNAME from ("+strSql+") ttt where ttt.flowname is not null ";
	    List typelist = flowtypeService.findAllBySql(typeSql);
	    
	    String returnStr = "[";
	    int m = 1;
	    for(int i=0;i<typelist.size();i++)
	    {
	    	Object[] typeitem = (Object[])typelist.get(i);
	    	returnStr+="{\"id\":\""+typeitem[0]+"\",\"text\":\""+typeitem[1]+"\",\"state\":\"closed\",\"children\":[";
	    	String itemSql = "select distinct FLOWNAME,statename,stateid from ("+strSql+") where FLOWNAME='"+typeitem[1]+"'";
	    	List itemlist = flowtypeService.findAllBySql(itemSql);
	    	for(int j=0;j<itemlist.size();j++)
	 	    {
	 	    	Object[] item = (Object[])itemlist.get(j);
	 	    	returnStr+="{\"id\":\""+item[2]+"\",\"text\":\""+item[1]+"\"},";
	 	    	m++;
	 	    }
	    	returnStr = returnStr.substring(0,returnStr.length()-1)+"]},";
	    }
	    returnStr = returnStr.substring(0,returnStr.length()-1)+"]";
	    
	    PrintWriter out = PubMethod.GetPrintWriter();
	    out.print(returnStr);
	}

	public IFlowtypeService getFlowtypeService() {
		return flowtypeService;
	}

	public void setFlowtypeService(IFlowtypeService flowtypeService) {
		this.flowtypeService = flowtypeService;
	}

 
}
